<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
window.updateCurrentTabName = (tabName) => {
  localStorage.setItem('currentTabName', tabName)
}

window.restoreScroll = (tabName) => {
  let pageScrollTopMap = localStorage.getItem('pageScrollTopMap')
  if (undefined === pageScrollTopMap || pageScrollTopMap === null || pageScrollTopMap === '') {
    pageScrollTopMap = {}
  } else {
    pageScrollTopMap = JSON.parse(pageScrollTopMap)
  }
  if (undefined !== pageScrollTopMap[tabName]) {
    // 保存切换tab时间
    pageScrollTopMap[tabName].lastSwitchTabTime = new Date().getTime()
    localStorage.setItem('pageScrollTopMap', JSON.stringify(pageScrollTopMap))
    // 滚动到原位置
    setTimeout(() => {
      if (undefined !== pageScrollTopMap[tabName].scrollTop) {
        // TODO 同个窗口多开时会导致滚动不执行，tabName确认过是不一样的
        window.frameElement.contentDocument.documentElement.scrollTop = pageScrollTopMap[tabName].scrollTop
        window.frameElement.contentDocument.body.scrollTop = pageScrollTopMap[tabName].scrollTop
      }
    }, 0)
  }
}

export default {
  name: 'App',
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
  },
  methods: {
    // 监听页面滚动位置用于恢复滚动条位置
    handleScroll() {
      setTimeout(() => {
        let pageScrollTopMap = localStorage.getItem('pageScrollTopMap')
        if (undefined === pageScrollTopMap || pageScrollTopMap === null || pageScrollTopMap === '') {
          pageScrollTopMap = {}
        } else {
          pageScrollTopMap = JSON.parse(pageScrollTopMap)
        }
        const currentTabName = localStorage.getItem('currentTabName')
        let lastSwitchTabTime
        if (undefined !== pageScrollTopMap[currentTabName]) {
          lastSwitchTabTime = pageScrollTopMap[currentTabName].lastSwitchTabTime
        }
        // 切换tab时会滚动到顶部，所以要延后1秒记录位置
        if (new Date().getTime() - lastSwitchTabTime < 1000) {
          return
        }
        let needSave = false
        if (undefined !== pageScrollTopMap[currentTabName]) {
          pageScrollTopMap[currentTabName].scrollTop = document.documentElement.scrollTop
          needSave = true
        } else {
          // 首次记录，滚动位置大于0才记录
          if (document.documentElement.scrollTop > 0) {
            pageScrollTopMap[currentTabName] = {
              scrollTop: document.documentElement.scrollTop,
              lastSwitchTabTime: 0
            }
            needSave = true
          }
        }
        if (needSave === true) {
          localStorage.setItem('pageScrollTopMap', JSON.stringify(pageScrollTopMap))
        }
      }, 150)
    }
  }
}
</script>
<style>
</style>
